package com.stylefeng.guns.modular.huamao.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.vod.upload.resp.UploadFileStreamResponse;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.modular.huamao.aliyun.OSSResultModel;
import com.stylefeng.guns.modular.huamao.common.FileUtils;
import com.stylefeng.guns.modular.huamao.model.SktClassDTO;
import com.stylefeng.guns.modular.huamao.service.IMessagesService;
import com.stylefeng.guns.modular.huamao.utils.VideoUtils;
import com.stylefeng.guns.core.util.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.modular.huamao.model.SktClass;
import com.stylefeng.guns.modular.huamao.service.ISktClassService;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.baomidou.mybatisplus.plugins.Page;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商学院控制器
 *
 * @author fengshuonan
 * @Date 2018-07-26 09:24:42
 */
@Controller
@RequestMapping("/sktClass")
public class SktClassController extends BaseController {

    private String PREFIX = "/huamao/sktClass/";

    @Autowired
    private ISktClassService sktClassService;

    @Autowired
    private FileUtils fileUtils;
    @Autowired
    private IMessagesService messagesService;
    /**
     * 跳转到商学院首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "sktClass.html";
    }

    /**
     * 跳转到添加商学院
     */
    @RequestMapping("/sktClass_add")
    public String sktClassAdd() {
        return PREFIX + "sktClass_add.html";
    }

    /**
     * 跳转到修改商学院
     */
    @RequestMapping("/sktClass_update/{sktClassId}")
    public String sktClassUpdate(@PathVariable Integer sktClassId, Model model) {
        SktClass sktClass = sktClassService.selectById(sktClassId);
        model.addAttribute("item",sktClass);
        LogObjectHolder.me().set(sktClass);
        return PREFIX + "sktClass_edit.html";
    }

    /**
     * 获取商学院列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(SktClassDTO sktClassDTO) {
        Page<SktClassDTO> page = new PageFactory<SktClassDTO>().defaultPage();
        List<SktClassDTO> sktClasses = sktClassService.selectSktClassAll(page, sktClassDTO);
        page.setRecords(sktClasses);
        return super.packForBT(page);
//        return sktClassService.selectList(null);
    }

    /**
     * 新增商学院
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(SktClass sktClass,HttpServletRequest request) {
        Map<String,Object> result = new HashMap<String, Object>();
        sktClass.setCreatTime(new Date());
        HttpSession session = request.getSession();
        SktClass sktClass1=sktClassService.selectSktClassByClassName(sktClass.getClassName());
        /*视频名称不可重复*/
        if (!StringUtils.isBlank(sktClass1)){
            result.put("code","-1");
            result.put("msg","名称有了");
            return result;
        }
        System.out.println(sktClass.toString()+"--------------------------");
        if (StringUtils.isBlank(sktClass.getClassTitle())){
            result.put("code","-1");
            result.put("msg","标题为空");
            return result;
        }
//        if (StringUtils.isBlank(sktClass.getClassImg())){
//            String videoImg = VideoUtils.getVideoImg(sktClass.getVideoId());
//            sktClass.setClassImg(videoImg);
//        }
//        if (sktClass.getClassUrl().equals("1")){
//            String classUrl = VideoUtils.getPlayUrl(sktClass.getVideoId());
//            sktClass.setClassUrl(classUrl);
//        }
        Map<String, Object> map = sktClassService.insertSktClass(sktClass);
        if (Integer.parseInt(map.get("status").toString())==1){
            return SUCCESS_TIP;
        }
        return ERROR;
    }
    @RequestMapping(value = "/uploadfile")
    @ResponseBody
    public Object uploadfile( HttpServletRequest request) throws  Exception {
        Map<String,Object> result = new HashMap<String, Object>();
        MultipartHttpServletRequest mReq  =  null;
        MultipartFile file = null;
        InputStream is = null ;
        OSSResultModel ossResult = null;
        String fileName = "";
        // 原始文件名   UEDITOR创建页面元素时的alt和title属性
        String originalFileName = "";

        try {
            mReq = (MultipartHttpServletRequest)request;
            // 从config.json中取得上传文件的ID
            file = mReq.getFile("fileName");
            // 取得文件的原
            fileName = file.getOriginalFilename();
            originalFileName = fileName;
            if(!com.alibaba.druid.util.StringUtils.isEmpty(fileName)){
                is = file.getInputStream();
                fileName = fileUtils.reName(fileName);
                ossResult = fileUtils.saveFile(fileName, is);
            } else {
                throw new IOException("文件名为空!");
            }
            String   classUrl = ossResult.getUrl();
            result.put("errno",0);
            result.put("classUrl",classUrl);
        }
        catch (Exception e) {
            result.put("errno",1);
            result.put("data","");
            System.out.println("文件 "+fileName+" 上传失败!");
        }
//        MultipartHttpServletRequest mReq = (MultipartHttpServletRequest) request;
//        HttpSession session = request.getSession();
//        MultipartFile file = mReq.getFile("fileName");
//        File f = File.createTempFile("fileName", file.getOriginalFilename());
//        file.transferTo(f);
//        String sysUrl = System.getProperty("java.io.tmpdir") + File.separator;
//        String fName = f.getName();
//        UploadFileStreamResponse response = VideoUtils.uploadVideo("视频课程", sysUrl + fName);
//        String videoId = response.getVideoId();
//        Object videoId1 = session.getAttribute("videoId");
//        if (!StringUtils.isBlank(videoId1)){
//            session.removeAttribute("videoId");
//        }
//        Object fileName = session.getAttribute("fileName");
//        if (!StringUtils.isBlank(fileName)){
//            session.removeAttribute("fileName");
//        }
//        session.setAttribute("videoId",videoId);
//        session.setAttribute("fileName",fName);
//
//        result.put("classUrl",VideoUtils.getPlayUrl(videoId));//此处需返回值
//        result.put("classvideoId",videoId);//此处需返回值
//        f.delete();

        return result;
    }
    /*public  void uploadfile(@RequestParam("fileName") MultipartFile multipartFile) throws  Exception{
//        String accessKeyId="LTAI0oVvPRNYwt4p";
//        String accessKeySecret="NoUX3bIHDKrdYRBuEOSkx4DkNSq9Fe";
        String originalFilename = multipartFile.getOriginalFilename();
        *//*CommonsMultipartFile commonsMultipartFile=(CommonsMultipartFile) multipartFile;
        String storageDescription = commonsMultipartFile.getStorageDescription();*//*
        File targetFile = new File(originalFilename);
//判断文件夹是否已经存在，如果已经存在了重新建
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        multipartFile.transferTo(targetFile);
        System.out.println(System.getProperty("java.io.tmpdir")+ File.separator+"--------------");
        String title=multipartFile.getOriginalFilename().substring(0,multipartFile.getOriginalFilename().lastIndexOf("."));
        String fileName=multipartFile.getOriginalFilename();
        System.out.println(multipartFile.getName()+"--------------");
        VideoUtils.uploadVideo(title,originalFilename);
        //   uploadVideoDemo.uploadfile(accessKeyId,accessKeySecret,title,fileName,inputStream);
    }*/



    /**
     * 删除商学院
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer sktClassId) {
        sktClassService.deleteById(sktClassId);
        return SUCCESS_TIP;
    }

    /**
     * 修改商学院
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(SktClass sktClass) {
        sktClassService.updateById(sktClass);
        return SUCCESS_TIP;
    }

    /**
     * 商学院详情
     */
    @RequestMapping(value = "/detail/{sktClassId}")
    @ResponseBody
    public Object detail(@PathVariable("sktClassId") Integer sktClassId) {
        return sktClassService.selectById(sktClassId);
    }


}
